﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools;
using Microsoft.Office.Tools.Word;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Office = Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
using WordTemplate1.Objets;
using Methodes.WordTemplate1;
using WordTemplate1.Methodes;

namespace WordTemplate1
{
    /// <summary>
    /// Element princial
    /// </summary>
    public partial class ThisDocument
    {
        #region Variable et propriété

        /// <summary>
        /// Panel Action permettant d'interragir avec la liste des workitems
        /// </summary>
        public UCPanel taskPanel = new UCPanel();

        /// <summary>
        /// Panel action permet d'être informer sur les modifications
        /// </summary>
        public UCInformation taskInformation = new UCInformation();

        /// <summary>
        /// Constante permet de centraliser la catégorie d'enregistrement des modèles
        /// </summary>
        private const string CATEGORIE = "TFSREQUIERMENT";
        /// <summary>
        /// Constant permettant de centraliser l'itendifiant des content
        /// </summary>
        public const string IDENTIFIANTCONTENT = "IDWI";

        /// <summary>
        /// Constant permettant de centraliser l'itendifiant des content
        /// </summary>
        public string IdentifiantContent
        {
            get { return IDENTIFIANTCONTENT; }
        } 

        /// <summary>
        /// Constante permet de centraliser la catégorie d'enregistrement des modèles
        /// </summary>
        public string CATEGORIE1
        {
            get { return CATEGORIE; }
        }


        #endregion Variable et propriété

        /// <summary>
        /// Démarage du document
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
            try
            {
                //Ajout des panel dans le document
                taskPanel.Dock = DockStyle.Fill;
                ActionsPane.Controls.Add(taskPanel);
                ActionsPane.Controls.Add(taskInformation);


                // Gestion des modifications des éléments
                this.BuildingBlockInsert += new DocumentEvents2_BuildingBlockInsertEventHandler(ThisDocument_BuildingBlockInsert);
                this.ContentControlOnExit += new DocumentEvents2_ContentControlOnExitEventHandler(ThisDocument_ContentControlOnExit);
                this.BeforeSave += new SaveEventHandler(ThisDocument_BeforeSave);
                this.ContentControlBeforeDelete += new DocumentEvents2_ContentControlBeforeDeleteEventHandler(ThisDocument_ContentControlBeforeDelete);
                this.ContentControlAfterAdd += new DocumentEvents2_ContentControlAfterAddEventHandler(ThisDocument_ContentControlAfterAdd);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Erreur (ERR_001) Team For Word", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void ThisDocument_BuildingBlockInsert(Range Range, string Name, string Category, string BlockType, string Template)
        {
            foreach (Microsoft.Office.Interop.Word.ContentControl cc in Range.ContentControls)
            {
                try
                {
                    bool etat = cc.LockContents;
                    cc.LockContents = false;
                    cc.Range.Text = String.Empty;
                    cc.LockContents = etat;
                }
                catch (Exception ex)
                {
                }
            }
        }


        /// <summary>
        /// Permet de valider la sortie du document
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ThisDocument_BeforeSave(object sender, SaveEventArgs e)
        {
            if (Globals.ThisDocument.taskInformation.lstInformation.Items.Count > 0)
            {
               DialogResult dr = MessageBox.Show("Attention des éléments ne sont pas synchronisés, Souhaitez vous fermer sans sauvegarder ?","Question ?",MessageBoxButtons.YesNo);
               if (dr == DialogResult.No)
               {
                   e.Cancel = true;
               }
            }
        }

        void ThisDocument_ContentControlAfterAdd(Word.ContentControl NewContentControl, bool InUndoRedo)
        {
            
        }

        void ThisDocument_ContentControlBeforeDelete(Word.ContentControl OldContentControl, bool InUndoRedo)
        {
            var linq = this.taskPanel.ListElement.Where(search => search.ContentcontrolsId.Count() > 0 && 
                               search.Type == TypeElement.Field);

            foreach (Element e in linq)
            {
                var element = from c in e.ContentcontrolsId
                                  where c == OldContentControl.ID
                                  select c;

                if (element.Count() > 0)
                    e.DeleteDocument(OldContentControl);
                
            }
        }

        /// <summary>
        /// Gestion des sortie des contents pour informer les éléments modifiés
        /// </summary>
        /// <param name="cc"></param>
        /// <param name="Cancel"></param>
        void ThisDocument_ContentControlOnExit(Word.ContentControl cc, ref bool Cancel)
        {
            if (cc.GetElement() != null)
            {
                RibbonTFSSpec re = (RibbonTFSSpec)Globals.Ribbons.GetRibbon(typeof(RibbonTFSSpec));

                if (re.cbxSynchro.Checked)
                {
                    this.ContentControls.Cast<Microsoft.Office.Interop.Word.ContentControl>()
                        .Where(contentControl => contentControl.Title == cc.Title
                            && contentControl.Range.Text != cc.Range.Text).ToList()
                            .ForEach(contentControl => contentControl.Range.Text = cc.Range.Text);
                }

                if(cc.GetElement() is EField)
                    ((EField)cc.GetElement()).Modify(cc);
            }

        }

        /// <summary>
        /// Permet d'ajouter un élément
        /// </summary>
        /// <param name="path"></param>
        public void AddImage(string path)
        {

            List<Microsoft.Office.Tools.Word.PictureContentControl> pictureControls = new List<Microsoft.Office.Tools.Word.PictureContentControl>();

            Microsoft.Office.Interop.Word.ContentControl content;
            content = this.ContentControls.Add(WdContentControlType.wdContentControlPicture);
            content.Title = "Image";

            Microsoft.Office.Tools.Word.PictureContentControl tempControl =
            this.Controls.AddPictureContentControl(content,
            "Image" + Guid.NewGuid().ToString());
            tempControl.Image = BitmapFromWeb(path);
            pictureControls.Add(tempControl);
        }

        /// <summary>
        /// Transformation de l'url de la PJ en image
        /// </summary>
        /// <param name="URL">Url de l'image</param>
        /// <returns>retourn l'image pour la coller dans le document</returns>
        public static Bitmap BitmapFromWeb(string URL)
        {
            try
            {
                // create a web request to the url of the image
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);

                myRequest.Credentials = TFS.tfsTP.Credentials;// new NetworkCredential("n.choulant", "n.choulant", "Evaluant");
                // set the method to GET to get the image
                myRequest.Method = "GET";
                // get the response from the webpage
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                // create a bitmap from the stream of the response
                Bitmap bmp = new Bitmap(myResponse.GetResponseStream());
                // close off the stream and the response
                myResponse.Close();
                // return the Bitmap of the image
                return bmp;
            }
            catch (Exception ex)
            {
                return null; // if for some reason we couldn't get to image, we return null
            }
        }


        /// <summary>
        /// Permet d'ajouter une propriété au document
        /// </summary>
        /// <param name="Title">Titre de la propriété</param>
        /// <param name="value">Valeur de la propriété</param>
        /// <param name="delete">Si false ne supprime pas si existant</param>
        public void AddProperties(string title, string value, bool delete)
        {
            Microsoft.Office.Core.DocumentProperties properties;

            properties = (Office.DocumentProperties)this.CustomDocumentProperties;

            if (delete)
            {
                if (ReadDocumentProperty(title) != null)
                {
                    properties[title].Delete();
                }

                properties.Add(title, false,
                    Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString,
                    value, missing);
            }
        }

        /// <summary>
        /// Permet de lire les propriétés du document
        /// </summary>
        /// <param name="propertyName">Nom de la propriété</param>
        /// <returns>retour la valeur</returns>
        public string ReadDocumentProperty(string propertyName)
        {
            Office.DocumentProperties properties;
            //return ((Office.DocumentProperties)this.CustomDocumentProperties).Cast<Office.DocumentProperty>()
            //    .Where(prop => prop.Name == propertyName).FirstOrDefault().Value.ToString();
            properties = (Office.DocumentProperties)this.CustomDocumentProperties;

            foreach (Office.DocumentProperty prop in properties)
            {
                if (prop.Name == propertyName)
                {
                    return prop.Value.ToString();
                }
            }
            return null;
        }

        /// <summary>
        /// Permet d'ajouter un block de données
        /// </summary>
        /// <param name="title">Titre du bloc</param>
        public void AddBlockType(string title)
        {
            Word.Template template1 = this.AttachedTemplate as Word.Template;

            if (template1 != null)
            {
                object description = null;
                template1.BuildingBlockEntries.Add(title,
                    Word.WdBuildingBlockTypes.wdTypeQuickParts, CATEGORIE,
                    this.Application.Selection.Range, ref description, Word.WdDocPartInsertOptions.wdInsertContent);

            }
        }

        /// <summary>
        /// Liste des bloc de la catégorie en constante
        /// </summary>
        /// <returns></returns>
        public List<BuildingBlock> GetAllBlockType()
        {
            List<BuildingBlock> liste = new List<BuildingBlock>();

            Word.Template template1 = this.AttachedTemplate as Word.Template;

            if (template1 != null)
            {
                for (int i = 0; i < template1.BuildingBlockEntries.Count; i++)
                {
                    try
                    {
                        BuildingBlock c = template1.BuildingBlockEntries.Item(i);
                        if (c.Category.Name == CATEGORIE)
                        {
                            liste.Add(c);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }

            }
            return liste;
        }


        private void ThisDocument_Shutdown(object sender, System.EventArgs e)
        {
            
        }

        #region Code généré par le Concepteur VSTO

        /// <summary>
        /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
        /// le contenu de cette méthode avec l'éditeur de code.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(this.ThisDocument_Startup);
            this.Shutdown += new System.EventHandler(this.ThisDocument_Shutdown);

        }

        #endregion

    }
}
